<?php

namespace Home\Controller;
use Common\Controller\Base;
use Common\Model\Model;
use Think\Controller;

class UcenterController extends Base {

    protected $uid;
    protected $openuid;

    protected function _initialize() {
        parent::_initialize();

        $this->openuid=I('get.openuid');
        if(getUidByOpenuid($this->openuid)){
            $this->uid=getUidByOpenuid($this->openuid);
        }else{
            $this->error('您无权访问当前页面!');
        }
        $this->assign('openuid',$this->openuid);

        //会员信息
        $this->memberDetail=D('Home/User')->find($this->uid);

        //烘焙作品数
        $this->hbworksnum=getCount('Works',array('userid'=>$this->uid,'type'=>1));

        //随拍作品
        $this->spworksnum=getCount('Copy',array('userid'=>$this->uid));

        //关注数
        $this->attentionnum=getCount('UserFans',array('myid'=>$this->uid));

        //被关注数
        $this->fansnum=getCount('UserFans',array('userid'=>$this->uid));

        //是否关注
        $this->isfans=getCount('UserFans',array('myid'=>$this->userid,'userid'=>$this->uid,'status'=>true));

        //中间广告
        $this->midad=parent::getAdvert(9,1,0,1);

    }

    //会员个人主页首页
    public function index(){

        $act=I('get.act');
        switch ($act){
            case 'works':
                $this->works();
                break;
            case 'suipai':
                $this->suipai();
                break;
            case 'favorite':
                $this->favorite();
                break;
            case 'message':
                $this->message();
                break;
            case 'fans':
                $this->fans();
                break;
            case 'attention':
                $this->attention();
                break;
            case 'copy':
                $this->copy();
                break;
            case 'teach':
                $this->teach();
                break;              
            default:
                $this->homeindex();
                break;
        }
        exit;

    }


    /**
     * 概况
     */
    public function homeindex(){
        //获取作品
//         $model=new Model();

//         $sql="select workid,title,image,copynum,favoritenum,type,copyid,copynum,clicknum,msgnum from ".C('DB_PREFIX')."works W where W.userid=".$this->uid." and W.status=true UNION select id as workid,title,image,'','','','','',clicknum,msgnum from ".C('DB_PREFIX')."suipai S where S.userid=".$this->uid." and S.status=true ORDER BY workid DESC";
//         $count=count($model->query($sql));

//         $page = $this->Pages($count, 15);
//         $page->url = '?page='.urlencode('[PAGE]');

//         $list=$model->query($sql." limit ".$page->firstRow . "," . $page->listRows."");

//         foreach ($list as $key=>$value) {
//             $list[$key]['dignum']=M('Dig')->where(array('status'=>true,'infoid'=>$value['workid'],'userid'=>$this->userid))->count();
//             $list[$key]['copyitem']=M('Works')->field('title,workid')->where(array('workid'=>$value['copyid']))->find();
//         }
//         $this->pagecount=$page->totalRows/$page->listRows;
//         $this->assign("list", $list);
//         $this->assign('datacount',$count);
//         $this->assign("Page", $page->show());
		
    	$suipai = M('Suipai');
    	$suipai_count = $suipai->where(array('userid' => $this->uid, 'status' => 1))->count();
    	$this->assign("suipai_count", $suipai_count);
    	$suipai_info = $suipai->where(array('userid' => $this->uid, 'status' => 1))->limit(18)->order('create_time desc')->select();
    	$this->assign("suipai_info", $suipai_info);
    	
    	$works = M('Works');
    	$works_count = $works->where("userid = %d and copyid is NULL and status=1", array($this->uid))->count();
    	$this->assign("works_count", $works_count);
    	$works_info = $works->where("userid = %d and copyid is NULL and status=1", array($this->uid))->limit(18)->order('create_time desc')->select();
    	$this->assign("works_info", $works_info);
    	
    	$copy_count = $works->where("userid = %d and copyid is NOT NULL and status=1", array($this->uid))->count();
    	$this->assign("copy_count", $copy_count);
    	$copy_info = $works->where("userid = %d and copyid is NOT NULL and status=1", array($this->uid))->limit(18)->order('create_time desc')->select();
    	$this->assign("copy_info", $copy_info);
    	
        $this->display('homeindex');
    }

    /**
     * 烘焙作品
     */
    public function works(){
        //获取作品
//         $where['status']=array('EQ',true);
//         $where['userid']=array('EQ',$this->uid);
//         $where['type']=array('EQ',1);
      //  $where['copyid']=array('EQ', "is NULL");
      	$where = "status = 1 and userid=".$this->uid." and type=1 and copyid is NULL";
        $url = __APP__.'/u/'.$this->openuid.'/works';
        $this->workslist($where,$url);
        $this->display('works');
    }
    
    public function copy(){
    	//获取作品
//     	$where['status']=array('EQ',true);
//     	$where['userid']=array('EQ',$this->uid);
//     	$where['type']=array('EQ',1);
    	//$where['copyid']=array('EQ', "is NOT NULL");
    	$where = "status = 1 and userid=".$this->uid." and type=2 and copyid is NOT NULL";
    	$url = __APP__.'/u/'.$this->openuid.'/copy';
    	$this->workslist($where,$url);
    	$this->display('copy');
    }

    /**
     * 随拍作品
     */
    public function suipai(){
        $where['status']=array('EQ',true);
        $where['userid']=array('EQ',$this->uid);
        $url = __APP__.'/u/'.$this->openuid.'/suipai';
        $worksModel=M('Suipai');
        $files=array('image','title','id','clicknum','msgnum');
        $count = $worksModel->where($where)->count();
        $page = $this->Pages($count, 15);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = $url.$pageurl;

        $list=$worksModel->where($where)->field($files)->limit($page->firstRow . ',' . $page->listRows)->order(array('id'=>'DESC'))->select();
        $this->pagecount=$page->totalRows/$page->listRows;
        $this->datacount=$count;
        $this->assign("list", $list);
        $this->assign("Page", $page->show());
        $this->display('suipai');
    }

    /**
     * 收藏
     */
    public function favorite(){
        $cate=I('get.cate',0,'intval');
        $model=new Model();
        if(empty($cate)){
            $listnav='全部产品';
            $where='';
            $url='';
        }else{
            $listnav=M('Category')->where(array('cateid'=>$cate))->getField('catename');
            $where=' and W.cateid='.$cate.'';
            $url='&cate='.$cate;
        }

        $count = $model->table(array(
            C('DB_PREFIX').'user_favorite'=>'F',
            C('DB_PREFIX').'works'=>'W'
        ))
            ->where('W.workid=F.infoid and F.status=true and F.userid='.$this->uid.$where.'')->count();

        $page = $this->Pages($count, 20);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = __APP__.'/u/'.$this->openuid.'/favorite'.$pageurl.$url;

        $favoritelist=$model
            ->table(array(
                    C('DB_PREFIX').'works'=>'W',
                    C('DB_PREFIX').'user_favorite'=>'F',
                    C('DB_PREFIX').'user'=>'U',
                )
            )
            ->where('W.workid=F.infoid and F.status=true and F.userid='.$this->uid.' and W.userid=U.userid'.$where.'')
            ->field('W.title,W.content,W.image,U.nickname,U.openuid,W.copynum,W.type,W.workid')
            ->order('F.create_time DESC')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();


        //显示类别
        $this->cate=$this->getCate();

        //列表
        $this->listnav=$listnav;
        $this->assign('favoritelist',$favoritelist);
        $this->assign("Page", $page->show());
        $this->display('favorite');
    }


    /**
     * 留言
     */
    public function message(){

        $model=new Model();
        $where['status']=true;
        $where['type']=2;
        $where['infoid']=$this->uid;
        $where['parent_id'] = 0;
        $count = M('UserMessage')->where($where)->count();

       // $limitRows = 5; // 设置每页记录数
        $limitRows = C('YF_PAGE');
        $page = $this->ajaxpage($count,$limitRows,'#msg','ajax_div','ajax_page_div');

        $msglist=$model
            ->table(array(
                    C('DB_PREFIX').'user_message'=>'M',
                    C('DB_PREFIX').'user'=>'U',
                )
            )
            ->where('M.status=true and M.type=2 and M.infoid='.$this->uid.' and M.userid=U.userid and M.parent_id=0')
            ->field('U.nickname,U.uprovince,U.ucity,U.openuid,U.uavatar,M.content,M.create_time,M.id,M.infoid,M.userid,M.touserid')
            ->order('M.create_time DESC')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

//         foreach($msglist as $k=>$v){
//             $msglist[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
//         }
            foreach($msglist as $k=>$v){
            	$child_temp = array();
            	$child_temp = $model->table(C('DB_PREFIX').'user_message')->field('*')->where(array('parent_id' => $v['id']))->order('create_time ASC')->select();
            
            	$msglist[$k]['childlist'] = array();
            	if($child_temp)
            	{
            		foreach($child_temp as $yk => $yv)
            		{
            			if($yv['userid'] == 0)
            			{
            				$child_temp[$yk]['nickname'] = "烘焙圈";
            				$child_temp[$yk]['openuid'] = 0;
            			}
            			else
            			{
            				$yf_user = array();
            				$yf_user = M('User')->field('openuid, nickname, uprovince, ucity, uavatar, ifrz')->where(array('userid'=>$yv['userid']))->find();
            				$child_temp[$yk]['nickname'] = $yf_user['nickname'];
            				$child_temp[$yk]['openuid'] = $yf_user['openuid'];
            				$child_temp[$yk]['uprovince'] = $yf_user['uprovince'];
            				$child_temp[$yk]['ucity'] = $yf_user['ucity'];
            				$child_temp[$yk]['uavatar'] = $yf_user['uavatar'];
            				$child_temp[$yk]['ifrz'] = $yf_user['ifrz'];
            			}
            			if($yv['touserid'] != 0)
            			{
            				$child_temp[$yk]['touser'] = M('User')->field('openuid,nickname')->where(array('userid'=>$yv['touserid']))->find();
            			}
            			else
            			{
            				$child_temp[$yk]['touser']['nickname'] = "烘焙圈";
            				$child_temp[$yk]['touser']['openuid'] = 0;
            			}
            		}
            		$msglist[$k]['childlist'] = $child_temp;
            	}
            	$msglist[$k]['tempname'] = hy_substr($v['nickname'], 4, true);
            	//$message[$k]['tempname'] = $v['nickname'];
            	$msglist[$k]['touser'] = array();
            	if(!empty($v['touserid']))
            	{
            		$msglist[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
            	}
            }
            unset($where['parent_id']);
            $this->msgcount=M('UserMessage')->where($where)->count();
        //列表
        $this->msgtype=2;
        $this->assign('msglist',$msglist);
        $this->assign('msgcount',$count);
        $this->assign("page", $page->show());

        $this->display('message');
    }


    /**
     * 获取作品列表
     * @param $where
     * @param $url
     */
    public function workslist($where,$url){
        $worksModel=M('Works');
        $files=array('image','title','workid','copynum','favoritenum','type','copyid','create_time');
        $count = $worksModel->where($where)->count();
        $page = $this->Pages($count, 15);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = $url.$pageurl;

        $list=$worksModel->where($where)->field($files)->limit($page->firstRow . ',' . $page->listRows)->order(array('workid'=>'DESC'))->select();

        foreach ($list as $key=>$value) {
            $list[$key]['dignum']=M('Dig')->where(array('status'=>true,'infoid'=>$value['workid'],'userid'=>$this->userid))->count();
            $list[$key]['copyitem']=$worksModel->field('title,workid')->where(array('workid'=>$value['copyid']))->find();
        }
        $this->pagecount=$page->totalRows/$page->listRows;

        $this->assign("list", $list);
        $this->assign('datacount',$count);
        $this->assign("Page", $page->show());
    }

    /**
     * 获取粉丝列表
     */
    public function fans(){
        $where['userid']=array('EQ',$this->uid);
        $where['status']=array('EQ',true);
        $userModel=M('UserFans');
        $count = $userModel->where($where)->count();
        $page = $this->Pages($count, 30);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = $pageurl;

        $model=new Model();
        $list=$model->table(array(
            C('DB_PREFIX').'user_fans'=>'F',
            C('DB_PREFIX').'user'=>'U',
        ))
            ->where('F.myid=U.userid and F.userid='.$this->uid.' and F.status=true')
            ->field('U.uavatar,U.nickname,U.openuid,F.userid,U.ifrz,F.myid')
            ->limit($page->firstRow . ',' . $page->listRows)->select();
        foreach($list as $key=>$value){
            $dynamic=M('UserDynamic')->field('create_time,content')->where(array('userid'=>$value['myid']))->order('id DESC')->find();
            $list[$key]['create_time']=$dynamic['create_time'];
            $list[$key]['content']=$dynamic['content'];
        }
        $this->assign("list", $list);
        $this->assign("Page", $page->show());
        $this->display('fans');
    }

    /**
     * 获取关注列表
     */

    public function attention(){
        $where['myid']=array('EQ',$this->uid);
        $where['status']=array('EQ',true);
        $userModel=M('UserFans');
        $count = $userModel->where($where)->count();
        $page = $this->Pages($count, 30);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = $pageurl;
        $model=new Model();
        $list=$model->table(array(
            C('DB_PREFIX').'user_fans'=>'F',
            C('DB_PREFIX').'user'=>'U',
        ))
            ->where('F.userid=U.userid and F.myid='.$this->uid.' and F.status=true')
            ->field('U.uavatar,U.nickname,U.openuid,F.userid,U.ifrz')
            ->limit($page->firstRow . ',' . $page->listRows)->select();

        foreach($list as $key=>$value){
            $dynamic=M('UserDynamic')->field('create_time,content')->where(array('userid'=>$value['userid']))->order('id DESC')->find();
            $list[$key]['create_time']=$dynamic['create_time'];
            $list[$key]['content']=$dynamic['content'];
        }

        $this->assign("list", $list);
        $this->assign("Page", $page->show());
        $this->display('attention');
    }
    
    public function teach()
    {
        if($this->memberDetail['ifds'] != 1)
        {
            $this->homeindex();
            exit;    
        }
        $is_user = 0;
        if($this->uid == $this->userid)
        {
            $is_user = 1;
        }
        $this->assign("is_user", $is_user);
        
        $fans_count = M('UserFans')->where(array('myid' => $this->uid, 'status' => 1))->count();
        $fans = M('UserFans')->where(array('myid' => $this->uid, 'status' => 1))->order('create_time desc')->limit(14)->select();
        if($fans)
        {
            foreach($fans as $k => $v)
            {
                $user = M('User')->where(array('userid' => $v['userid']))->field('openuid, uavatar, nickname')->find();
                $fans[$k]['nickname'] = $user['nickname'];
                $fans[$k]['openuid'] = $user['openuid'];
                $fans[$k]['uavatar'] = $user['uavatar'];
            }
        }
        
        $is_fans = M('UserFans')->where(array('userid' => $this->uid, 'status' => 1))->count();
        $this->assign("is_fans", $is_fans);
        
        $is_tj = M('User')->where(array('ifrz' => 1))->order('login_time desc')->limit(4)->select();
        if($is_tj)
        {
            foreach($is_tj as $tk => $tv)
            {
                $is_tj[$tk]['nickname'] = hy_substr($tv['nickname'], 5);
            }
        }
        $this->assign("is_tj", $is_tj);
        
        $this->assign("fans_count", $fans_count);
        $this->assign("fans", $fans);
        
        $type = I('get.type');
        if(empty($type))
        {
            $type = 1;
        }
        $this->assign("type", $type);
        
        if($type == 1)
        {
            $data_time = M('Teachlist')->where(array('userid' => $this->uid, 'type' => $type))->order('create_time desc')->field('teachid, create_time')->select();
            $data_date = array();
            if($data_time)
            {
                foreach($data_time as $dk => $dv)
                {
                    $year = $data_time[$dk]['year'] = date('Y', $dv['create_time']);
                    $month = $data_time[$dk]['month'] = date('m', $dv['create_time']);
                    $day = $data_time[$dk]['day'] = date('d', $dv['create_time']);
                    $data_date[] = $data_time[$dk]['time'] = strtotime($year."-".$month."-".$day);
                }
                $data_date = array_unique($data_date);
            }
            $data_temp = array();
            if($data_date)
            {
                $arr = array();
                foreach($data_date as $ak => $av)
                {
                    $arr[] = $av;
                }
                foreach($arr as $ddk => $ddv)
                {
                    $data_temp[$ddk]['year'] = date('Y', $ddv);
                    $data_temp[$ddk]['month'] = date('m', $ddv);
                    $data_temp[$ddk]['day'] = date('d', $ddv);
                    foreach($data_time as $dtk => $dtv)
                    {
                        if($dtv['time'] == $ddv)
                        {
                            $info = M('Teachlist')->where(array('teachid' => $dtv['teachid']))->field('teachid, type, userid, title, viewnum, msgnum, create_time, content')->find();
                            preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', htmlspecialchars_decode($info['content']), $match);
                            if($match[0])
                            {
                                $info['image'] = $match[2];
                            }
                            $info['title'] = hy_substr($info['title'], 20, true);
                            $info['uavatar'] = M('User')->where(array('userid' => $info['userid']))->getField('uavatar');
                            $info['favnum'] = M('Teachfav')->where(array('infoid' => $info['teachid'], 'type' => 7, 'status' => 1))->count();
                            $data_temp[$ddk]['teachlist'][] = $info;
                        }
                    }
                }
            }
            
            $ypage = I('get.page');
            if(empty($ypage))
            {
                $ypage = 1;
            }
            $count = count($data_temp);
            $page = $this->Pages($count, 5);
            $pageurl='?type='.$type.'page='.urlencode('[PAGE]');
            $page->url     = __APP__.'/u/'.$this->openuid.'/teach'.$pageurl;
            
            $list = array();
            $start = ($ypage-1)*$page->listRows;
            $first = 0;
            $temp_first = 0;
            for($i = $start; $i < ($start + $page->listRows); $i++)
            {
                if(!empty($data_temp[$i]))
                {
                    if($temp_first == 0 || $temp_first != $data_temp[$i]['year'])
                    {
                        $data_temp[$i]['is_sign'] = 1;
                        $temp_first = $data_temp[$i]['year'];
                        $first = 1;
                    }
                    elseif($temp_first == $data_temp[$i]['year'])
                    {
                        if($first == 0)
                        {
                            $data_temp[$i]['is_sign'] = 1;
                            $temp_first = $data_temp[$i]['year'];
                            $first = 1;
                        }
                    }
                    $list[] = $data_temp[$i];
                }
            }//print_r($list);
        }
        else 
        {
            $count = M('Teachlist')->where(array('userid' => $this->uid, 'type' => 2, 'status' => 1))->count();
            $page = $this->Pages($count, 10);
            $pageurl='?type='.$type.'page='.urlencode('[PAGE]');
            $page->url     = __APP__.'/u/'.$this->openuid.'/teach'.$pageurl;
            $list = M('Teachlist')->where(array('userid' => $this->uid, 'type' => 2, 'status' => 1))->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
            if($list)
            {
                foreach($list as $lk => $lv)
                {
                    $list[$lk]['title'] = hy_substr(strip_tags(htmlspecialchars_decode($lv['title'])), 30, true);
                    $list[$lk]['desc'] = hy_substr(strip_tags(htmlspecialchars_decode($lv['content'])), 100, true);
                }
            }
        }
        $this->pagecount=$page->totalRows/$page->listRows;
      
        $this->assign("list", $list);
        $this->assign("Page", $page->show());
        
        $zuopin = M('Teachlist')->where(array('userid' => $this->uid, 'type' => 1))->count();
        $article = M('Teachlist')->where(array('userid' => $this->uid, 'type' => 2))->count();
        $this->assign("zuopin", $zuopin);
        $this->assign("article", $article);
        
        $this->display('teach');
    }

}